﻿using System;
using System.Collections.Generic;
using System.Text;
using Fsb.Utility;
using VideoCache.Spider.Baidu;
using Newtonsoft.Json.Linq;

namespace VideoCache.Spider
{
    public class SpiderFactory
    {
        const string URL = "http://video.baidu.com/v?word={0}";

        public static BaiduAlbum[] SearchAlbum(string keyword)
        {
            string url = string.Format(URL, HttpUtility.UrlEncode(keyword, Encoding.GetEncoding("gb2312")));

            string html = HttpUtility.Get(url, Encoding.GetEncoding("gb2312"));

            string scriptContent = StringUtility.SubString(html, "globalVars.aldJson = [];", "var isResult").Trim();

            List<BaiduAlbum> albumList = new List<BaiduAlbum>();

            if (scriptContent.Length > 0)
            {
                string[] list = scriptContent.Split(new string[] { "globalVars.aldJson.push(T.object.extend(" }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 1; i < list.Length; i++)
                {
                    string itemJson = StringUtility.SubString(list[i], "", ", {\"alias\"");
                    if (!string.IsNullOrEmpty(itemJson))
                    {
                        BaiduAlbum album = JsonUtility.Object<BaiduAlbum>(itemJson);
                        albumList.Add(album);
                    }
                }
            }

            return albumList.ToArray();
        }

        public static SpiderAlbum GetEpisodes(BaiduAlbumType type, int id)
        {
            string json = string.Empty;
            switch (type)
            {
                case BaiduAlbumType.Movie:
                    return GetMovieIntro(id);
                case BaiduAlbumType.Tv:
                    return GetTvIntro(id);
                default:
                    throw new NotImplementedException();
            }

            return null;
        }

        private static SpiderAlbum GetTvIntro(int id)
        {
            string url = "http://video.baidu.com/tv_intro/?dtype=tvPlayUrl&service=json&id={0}";
            url = string.Format(url, id);
            string json = HttpUtility.Get(url, Encoding.GetEncoding("gb2312"));

            SpiderAlbum album = new SpiderAlbum();

            JObject obj = Newtonsoft.Json.Linq.JObject.Parse(json);

            foreach (KeyValuePair<string, JToken> item in obj)
            {
                SpiderSite site = new SpiderSite();
                site.SiteUrl = item.Value["site_info"]["site"].ToString().Trim('\"');
                site.SiteName = item.Value["site_info"]["name"].ToString().Trim('\"');
                album.Sites.Add(site);

                JArray episodes = item.Value["episodes"] as JArray;

                foreach (var episode in episodes)
                {
                    SpiderVideo video = new SpiderVideo();
                    video.Episode = Convert.ToInt32(episode["episode"].ToString().Trim('\"'));
                    video.Url = episode["url"].ToString().Trim('\"');
                    video.Name = episode["single_title"].ToString().Trim('\"');

                    site.Videos.Add(video);
                }
            }

            return album;
        }

        private static SpiderAlbum GetMovieIntro(int id)
        {
            string url = "http://video.baidu.com/{0}/?dtype=playUrl&service=json&id={1}&page=1";
            url = string.Format(url, "movie_intro", id);
            string json = HttpUtility.Get(url, Encoding.GetEncoding("gb2312"));

            var list = JsonUtility.Object<BaiduMovieSite[]>(json);

            if (list == null) throw new Exception("无法找到视频地址。");

            SpiderAlbum album = new SpiderAlbum();
            foreach (var item in list)
            {
                SpiderSite site = new SpiderSite();
                site.SiteUrl = item.Site;
                site.SiteName = item.Name;
                album.Sites.Add(site);

                SpiderVideo video = new SpiderVideo();
                video.Episode = 1;
                video.Url = item.Link;
                site.Videos.Add(video);
            }

            return album;
        }

        private static BaiduEpisodeInfo[] GetEpisodesWithoutMovie(BaiduAlbumType type, int id, string site_url)
        {
            string url = "http://video.baidu.com/{0}/?id={1}&site={2}";

            switch (type)
            {
                case BaiduAlbumType.Tv:
                    url = string.Format(url, "htvplaysingles", id, site_url);
                    break;
                case BaiduAlbumType.ZongYi:
                    url = string.Format(url, "htvshowsingles", id, site_url);
                    break;
                case BaiduAlbumType.Dongman:
                    url = string.Format(url, "hcomicsingles", id, site_url);
                    break;
                default:
                    throw new NotImplementedException();
            }

            string json = HttpUtility.Get(url, Encoding.GetEncoding("gb2312"));

            BaiduSiteCollection siteColl = JsonUtility.Object<BaiduSiteCollection>(json);

            if (siteColl != null)
            {
                return siteColl.videos;
            }

            return null;
        }
    }
}